<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="表名" prop="tableName">
        <el-input v-model="queryParams.tableName" placeholder="请输入表名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="表备注" prop="tableDesc">
        <el-input v-model="queryParams.tableDesc" placeholder="请输入表备注" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="主键字段名" prop="primaryKeyName">
        <el-input v-model="queryParams.primaryKeyName" placeholder="请输入主键字段名" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['sa:data-permission-define:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['sa:data-permission-define:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="说明" align="center" prop="tableDesc" min-width="150" show-overflow-tooltip/>
      <el-table-column label="表名" align="center" prop="tableName" min-width="150" show-overflow-tooltip>
        <template v-slot="scope">
          <router-link :to="'/data-permission-define/item/' +  scope.row.id" class="link-type"
                       v-hasPermi="['sa:data-permission-define:update']">
            <span>{{ scope.row.tableName }}</span>
          </router-link>
          <sapn v-if="!checkPermi(['sa:data-permission-define:update'])">{{ scope.row.tableName }}</sapn>
        </template>
      </el-table-column>
      <el-table-column label="主键" align="center" prop="primaryKeyName" min-width="80" show-overflow-tooltip/>
      <el-table-column label="备注" align="center" prop="nameKey" min-width="150" show-overflow-tooltip/>
      <el-table-column label="外键" align="center" prop="foreignKeyName" min-width="120" show-overflow-tooltip/>
      <el-table-column label="父节点" align="center" prop="parentIdKeyName" min-width="120" show-overflow-tooltip/>
      <el-table-column label="根的值" align="center" prop="rootId" min-width="120" show-overflow-tooltip/>
      <el-table-column label="创建人" align="center" prop="creator"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updater"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="120">
        <template v-slot="scope">
          <!--          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                               :to="'/data-permission-define/item/' + scope.row.id"
                                         v-hasPermi="['sa:data-permission-define:update']">添加权限项
                              </el-button>-->

          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['sa:data-permission-define:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['sa:data-permission-define:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="800px" v-dialogDrag append-to-body>
      <el-row>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-col :span="12" :xs="24">
            <el-form-item prop="tableName">
              <span slot="label">
                <el-tooltip content="" placement="top">
                   <div slot="content">
                     1、如果是物理表名，则可以不用配置SQL取数脚本，而直接从指定表获取数据<br/>
                     2、如果不是物理表名，则必须指定SQL取数脚本，否则无法配置数据权限<br/>
                   </div>
                  <i class="el-icon-question"/>
                </el-tooltip>
                表名
              </span>
              <el-input v-model="form.tableName" placeholder="请输入表名:system_dept"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="表说明" prop="tableDesc">
              <el-input v-model="form.tableDesc" placeholder="请输入表备注:系统部门表"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item prop="primaryKeyName">
              <span slot="label">
                <el-tooltip content="" placement="top">
                   <div slot="content">
                     1、获取权限数据时，该字段作为数据主键<br/>
                     2、权限控制时，当目标表与定义表名相同时，将该字段作为默认的控制字段<br/>
                   </div>
                  <i class="el-icon-question"/>
                </el-tooltip>
                主键字段名
              </span>
              <el-input v-model="form.primaryKeyName" placeholder="请输入主键字段名：id"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="名称字段名" prop="nameKey">
              <el-input v-model="form.nameKey" placeholder="请输入备注字段名：name"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="外键字段名" prop="foreignKeyName">
              <span slot="label">
                <el-tooltip content="" placement="top">
                   <div slot="content">
                     权限控制时，若当目标表与定义表名不相同时，将该字段作为目标表控制字段，另外也可通过注解的targetColumn指定，targetColumn具有高优先级。<br/>
                   </div>
                  <i class="el-icon-question"/>
                </el-tooltip>
                外键字段名
              </span>
              <el-input v-model="form.foreignKeyName" placeholder="请输入外键字段名：dept_id"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="父节点字段名" prop="parentIdKeyName">
              <span slot="label">
                <el-tooltip content="" placement="top">
                   <div slot="content">
                     获取权限数据时，若有配置parentId字段，则配置数据权限时以树形结构展示。<br/>
                   </div>
                  <i class="el-icon-question"/>
                </el-tooltip>
                父节点字段名
              </span>
              <el-input v-model="form.parentIdKeyName" placeholder="请输入父节点字段名：parent_id"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="根的值" prop="rootId">
              <span slot="label">
                <el-tooltip content="" placement="top">
                   <div slot="content">
                     对于树形结构来说，是一级节点的父级节点的值，用于解析出根结点;<br/>
                     非树结构数据不需要<br/>
                   </div>
                  <i class="el-icon-question"/>
                </el-tooltip>
                根的值
              </span>
              <el-input v-model="form.rootId" placeholder="请输入根节点的值"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="" prop="isDbTable">
              <span slot="label">
                <el-tooltip content="" placement="top">
                   <div slot="content">
                     选择是物理表：则表名与数据库表名一致，给方法添加权限注释时，可不需要指定目标表，而使用这里的物理表名进行权限匹配<br/>
                     选择非物理表：表名字段可为任意编码，给方法添加权限注释时，必须targetTable属性用来指定目标表，否则会抛出异常<br/>
                   </div>
                  <i class="el-icon-question"/>
                </el-tooltip>
                是否物理表
              </span>
              <el-radio-group v-model="form.isDbTable">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.SA_YES_NO)"
                          :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" :xs="24">
            <el-form-item label="SQL脚本">
              <span slot="label">
                <el-tooltip content="" placement="top">
                   <div slot="content">
                     自定义权限控制数据取数脚本,若配置了脚本,优先通过脚本取数<br/>
                     若未定义脚本,使用表名取数<br/>
                     若未定义脚本,表名也不是物理表,则取数抛出异常,影响数据权限配置.<br/>
                   </div>
                  <i class="el-icon-question"/>
                </el-tooltip>
                SQL脚本
              </span>
              <el-input type="textarea" v-model="form.sqlScript" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createDataPermissionDefine,
  updateDataPermissionDefine,
  deleteDataPermissionDefine,
  getDataPermissionDefine,
  getDataPermissionDefinePage,
  exportDataPermissionDefineExcel
} from "@/api/sa/dataPermissionDefine";
import Editor from '@/components/Editor';

export default {
  name: "DataPermissionDefine",
  components: {Editor},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用来定义哪些业务表用来做权限控制，如部门表、费用科目、项目表。一般用来控制权限的都是基础数据表。列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        tableName: null,
        tableDesc: null,
        primaryKeyName: null,
        nameKey: null,
        parentIdKeyName: null,
        foreignKeyName: null,
        version: null,
        createdTime: [],
        updatedTime: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tableName: [{required: true, message: "表名不能为空", trigger: "blur"}],
        primaryKeyName: [{required: true, message: "主键字段名不能为空", trigger: "blur"}],
        tableDesc: [{required: true, message: "主键字段名不能为空", trigger: "blur"}],
        nameKey: [{required: true, message: "名称字段名不能为空", trigger: "blur"}],
        foreignKeyName: [{required: true, message: "外键字段名不能为空", trigger: "blur"}],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getDataPermissionDefinePage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        tableName: undefined,
        tableDesc: undefined,
        primaryKeyName: undefined,
        rootId: undefined,
        nameKey: undefined,
        sqlScript: undefined,
        parentIdKeyName: undefined,
        foreignKeyName: undefined,
        version: undefined,
        createdTime: undefined,
        updatedTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据权限表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getDataPermissionDefine(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "添加数据权限表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateDataPermissionDefine(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createDataPermissionDefine(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除数据权限表。编号为"' + id + '"的数据项?').then(function () {
        return deleteDataPermissionDefine(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出数据权限表。数据项?').then(() => {
        this.exportLoading = true;
        return exportDataPermissionDefineExcel(params);
      }).then(response => {
        this.$download.excel(response, '数据权限表。.xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>
